package proj.pt.web;

import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.springframework.validation.BindException;
import org.springframework.validation.Errors;
import org.springframework.web.bind.ServletRequestDataBinder;

import proj.pt.model.Course;
import proj.pt.model.SubCourse;
import proj.pt.model.User;

public class ExamListController extends CustomSimpleFormController {

	protected Map referenceData(HttpServletRequest request, Object command, Errors errors) throws Exception {
		Map dataMap = super.referenceData(request, command, errors);
		
		dataMap.put("examTypes", getLogicProcessor().getExamTypes());
		User currentUser = (User)dataMap.get("currentUser");
		
		ExamFilter filter = (ExamFilter)command;
		if(filter.getCourse() != null){
			// get semester based on course,
			dataMap.put("semesters", getLogicProcessor().getSubCourses(filter.getCourse()));
			
			// if semester also chosen,  then filter subject by semester.
			if(filter.getSubCourse() != null){
				dataMap.put("exams", getLogicProcessor().getExams(currentUser, filter.getSubCourse(), filter.getExamType()));
			} //end if
		} // end if
		
		dataMap.put("examTypes", getLogicProcessor().getExamTypes());
		
		
		dataMap.put("courses", getLogicProcessor().getCourses(currentUser));
		
		return dataMap;
	} //end referenceData
	
	
	protected void initBinder(HttpServletRequest request, ServletRequestDataBinder binder) throws Exception {
		binder.registerCustomEditor(SubCourse.class, "subCourse", new SubCourseEditor(getLogicProcessor()));
		binder.registerCustomEditor(Course.class, "course", new CourseEditor(getLogicProcessor()));
	}
	
	
	/**
	 * This method does the validation.
	 */
	protected void onBindAndValidate(HttpServletRequest request,
            Object command,
            BindException errors) throws Exception {
		
		// if no validation required, then just return from this method.
		if(!doValidate(request))return;
		
		ExamFilter filter = (ExamFilter)command;
		
		if(filter.getCourse() == null){
			errors.reject("course.required", "Please select a course.");
		} else if(filter.getSubCourse() == null){
			errors.reject("semester.required", "Please select a semester.");
		} //end else if
	}
	
}
